package array;

/**
 * 二分查找
 * @author liumingju
 * @date 2025/2/14 11:58
 */
public class 二分查找 {

    public static void main(String[] args) {
        int[] arr = {1,3,5,7,9,12,13};
        //int i = binarySelect(arr, 13);
        int i = binarySelect02(arr, 18);
        System.out.println(i);
    }


    // 左闭右闭区间
    public static int binarySelect(int[] arr,int target){
        int l = 0;
        int r = arr.length-1;
        int mid = (l+r)/2;
        while(l<=r){
            if(arr[mid]>target){
                // 向左边查找
                r = mid-1;
            }else if(arr[mid]<target){
                l = mid+1;
            } else if(arr[mid]==target){
                return mid;
            }
            mid = (l+r)/2;
        }
        return -1;
    }

    // 左闭右开区间
    public static int binarySelect02(int[] arr,int target){
        int left = 0;
        int right = arr.length;
        int mid = (left+right)/2;
        while (left<right){
            if(arr[mid] == target){
                return mid;
            } else if (target<arr[mid]) {
                right= mid;
            } else {
                left = mid+1;
            }
            mid = (left+right)/2;
        }
        return -1;
    }
}
